import {
  wxRequest
} from '../../../utils/server.js'; 
const _wxRequest = new wxRequest(); 
import goods_share from "../../../component/painter/palette/goods";
const goodsShare = new goods_share()
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    uploadUrl: wx.getStorageSync('uploadUrl'),
    imageWidth: wx.getSystemInfoSync().windowWidth,
    adList: [],
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示 
      // title: '商品详情', //导航栏 中间的标题
    },
    height: app.globalData.height * 2 + 20,
    goodsTabId: 1,
    num: 1,
    cardCur: 0,
    id: '',
    swiperList: [],
    goodsTabId: 1,
    show: false,
    mdc_show: false,
    arrt: false,
    assessList: [],
    defaultAddress: {},
    buyNowflag:false,
    shareStart:false
  },

  onLoad: function(options) { 
    var pramas = options 
    var obj = wx.getLaunchOptionsSync()  
    //通过分享进来
    if (options.scene) {  
      this.decodeShort(options.scene)
    }else{ 
      this.repramas(pramas) 
    } 
  },



  //解析参数
  repramas: function (pramas){
    this.setData({
      id: pramas.id,
      sharedCusId: pramas.sharedCusId || '',
      empUserId: pramas.empUserId || ''
    })

    if (pramas.sharedCusId) {
      wx.removeStorageSync('empUserId')
      wx.setStorageSync('sharedCusId', pramas.sharedCusId)
    }

    if (pramas.empUserId) {
      wx.removeStorageSync('sharedCusId')
      wx.setStorageSync('empUserId', pramas.empUserId)
    }  


    if (pramas.id) {
      console.log('jing')
      this.getDetail();
      this.findGoodsListByGroupId(); //推荐商品

      if (wx.getStorageSync('Authorization')) {
        this.getGoodsAttend(); //关注商品
        this.getDefaultAddress();
        this.updateGdsId()
      }
    } 
  },

  //将短码解码成长码
  decodeShort(scene) {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/sys/comm/decodeShort',
      method: 'POST',
      data: {
        shortCode: scene
      }

    }, (res) => {
      var longCode = res.longCode
      var pramas = _wxRequest.urlScene(decodeURIComponent(longCode))
      this.repramas(pramas)
      console.log(res,'decodeShort')
    })
  },
 

  //获取产品详情
  getDetail: function() {
    console.log('getDetail')
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/gds/goods/detail2?id=' + this.data.id,
      method: 'POST'
    }, (res) => {
      var detailVo = res.vo;
      var assessList = detailVo.assessList;
      assessList.map(item => {
        item.imgJson = JSON.parse(item.imgJson)
        //头像
        var avatar = item.avatar
        if (avatar && avatar.indexOf('https') != 0) {
          item.avatar = this.data.uploadUrl + item.avatar
        }
      })

      this.setData({
        detail: detailVo,
        adList: detailVo.coverImgs,
        assessList: assessList
      })
    })

  },

  //切换sku
  skuCheck: function(e) {
    var id = e.currentTarget.dataset.id
    this.setData({
      id
    })
    this.getDetail()
  },

  // tab切换
  checkTab(e) {
    var goodsTabId = e.currentTarget.dataset.id
    this.setData({
      goodsTabId: goodsTabId
    })
  },

  onClickButton: function() {
    Toast('点击按钮');
  },

  //弹窗选择sku选择
  showPopup: function() {
    this.setData({
      show: true
    });
  },

  //关闭弹窗
  onClose: function() {
    this.setData({
      show: false,
      buyNowflag: false
    });
  },

  //更新数量 
  hadleNumChange: function(e) {
    this.setData({
      num: e.detail
    })
  },

  //加入购物车
  addCate: function() {
    var params = {
      gdsId: this.data.id,
      qty: this.data.num,
      sharedCusId: this.data.sharedCusId || wx.getStorageSync('sharedCusId'),
      inviteStoId: this.data.inviteStoId || wx.getStorageSync('inviteStoId'),
      empUserId: this.data.empUserId || wx.getStorageSync('empUserId')
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/shoppingCart/add',
      method: 'post',
      data: params
    }, (res) => {
      wx.showToast({
        title: '加入购物车成功',
      })
    })
  },

  buyNowfun:function(){
    this.setData({
      show:true,
      buyNowflag:true
    })
  },


  //立即购买
  buyNow: function() {
    var params = {
      gdsId: this.data.id,
      qty: this.data.num,
      sharedCusId: this.data.sharedCusId || wx.getStorageSync('sharedCusId'),
      inviteStoId: this.data.inviteStoId || wx.getStorageSync('inviteStoId'),
      empUserId: this.data.empUserId || wx.getStorageSync('empUserId')
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/shoppingCart/buyNow',
      method: 'post',
      data: params
    }, (res) => {
      console.log(data, 'datadata')
      var data = res.vo;
      data.price = data.intoPrice
      data.qty = this.data.num

      var goodsOdrList = [];
      var odrTotalPrice = (data.qty * data.intoPrice).toFixed(2)

      goodsOdrList.push(data)
      wx.setStorageSync('goodsOdrList', goodsOdrList)
      wx.setStorageSync('odrTotalPrice', odrTotalPrice)

      wx.navigateTo({
        url: '/pages/settle/index',
      })

    })
  },


  //推荐商品 
  findGoodsListByGroupId: function() {
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/gds/goods/recommend',
      method: 'POST',
      data: {
        gdsId: this.data.id,
        pageNo: 1,
        pageSize: 8
      } 
    }, (res) => {
      var list = res.list;
      var newarr = this.group(list, 3)
      this.setData({
        swiperList: newarr
      })
    })
  },

  group: function(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while (index < array.length) {
      newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
  },

  //更多商品
  toGoodsList: function() {
    wx.navigateTo({
      url: '/pages/good/list/index',
    })
  },

  //预览户型图
  imageList: function(e) {
    let current = this.data.uploadUrl + e.target.dataset.src;
    let urls = e.target.dataset.urls;
    if (urls && urls.length) {
      for (var i = 0; i < urls.length; i++) {
        urls[i] = this.data.uploadUrl + urls[i].imgPath
      };
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    });
  },

  



  // 封面点击的时候相应的操作  获取视频在JS里的参数属性 
  //重点：点击图片接下来视频进行播放，但是视频播放后直接触发了视频的pause() 结局的方案是，延时150ms后再进行视频的播放，就完美解决了
  bindPlay: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.index

    // 没有播放时播放视频
    if (!this.data.playIndex) {
      this.setData({
        playIndex: id
      })
      var videoContext = wx.createVideoContext(id) //这里对应的视频id
      videoContext.play()
    } else { // 有播放时先将prev暂停，再播放当前点击的current 
      var videoContextPrev = wx.createVideoContext(this.data.playIndex)
      if (this.data.playIndex != id) {
        videoContextPrev.pause()
      }
      this.setData({
        playIndex: id
      })
      var videoContextCurrent = wx.createVideoContext(id)
      videoContextCurrent.play()
    }


    that.setData({
      mdc_show: true
    })

  },

  outPlay: function () {
    this.setData({
      mdc_show: false
    })
  },


  //安卓系统能检测到 video touchemove 滑动的x距离，已此作为切换的swiper的凭证
  //ios系统，检测不到video touchemove 滑动的x距离，通过cover-view 点击事件进行切换
  mdc_move1: function(e) {
    var that = this;
    console.log(e)
    console.log(e.touches[0].pageX)
    var videoContextPrev = wx.createVideoContext('mdcVideo1');
    videoContextPrev.pause()
    if (e.touches[0].clientX > 20) {
      that.setData({
        mdc_show: false,
      })
    }
  },
  returnquanping: function(e) {
    var that = this;
    that.setData({
      mdc_show: false,
    })
  },

  //评价
  moreAssess: function(e) {
    var item = e.target.dataset.assessStatistics;
    var type = e.target.dataset.type || ''
    wx.navigateTo({
      url: '/pages/good/detail/assess?gdsId=' + this.data.id + '&type=' + type,
    })
  },


  //关注商品 
  customerAttend: function() {
    var that = this;
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goodsAttend/addCustomerAttend?gdsId=' + this.data.id,
      method: 'post'
    }, (res) => {
      that.setData({
        arrt: true
      })

      wx.showToast({
        icon: 'none',
        title: '收藏成功'
      })
    })
  },

  //取消关注
  delCustomerAttend: function() {
    var that = this;
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goodsAttend/deleteCustomerAttend?gdsId=' + this.data.id + '&gdsIdList=' + [this.data.id],
      method: 'post'
    }, (res) => {
      that.setData({
        arrt: false
      })
      wx.showToast({
        icon: 'none',
        title: '取消收藏'
      })
    })
  },


  // 查询商品关注
  getGoodsAttend: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/goodsAttend/existsCustomerAttend?gdsId=' + this.data.id,
      method: 'POST'
    }, (res) => {
      this.setData({
        arrt: res.flag
      })
    })
  },

  //获取默认地址
  getDefaultAddress: function() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/customerAddress/defaultAddress',
      method: 'POST',
      data: {}
    }, (res) => {
      this.setData({
        defaultAddress: res.vo
      })
    })
  },


  //获取当前地址
  getLocation: function() {
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
      }
    })
  },
 

  //分享 
  onShareAppMessage: function () {
    this.setData({
      shareStart: !this.data.shareStart
    })
    
    var image = this.data.uploadUrl + this.data.detail.coverImgs[0].imgPath;
    var uId = wx.getStorageSync('userInfo').id || '' ;
    var goodsName = this.data.detail.goodsName     
    return {
      title: goodsName,
      imageUrl: image,
      path: '/pages/good/detail/index?id=' + this.data.id + '&sharedCusId=' + wx.getStorageSync('userInfo').id
    } 
  
  },

  updateGdsId: function () {
    var that = this;
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/odr/protected/customer/updateGdsId?gdsId=' + this.data.id,
      method: 'post'
    }, (res) => {
      
    })
  },

  //点击分享
  clickShare:function(){
    this.setData({
      shareStart: !this.data.shareStart
    })
  },

  //下载 
  saveImg: function () {
    var that = this;  
    wx.showToast({
      title: '素材加载中',
      icon: 'loading'
    }) 
    this.setData({
      shareStart: !this.data.shareStart
    })
    var n=0
    for (var i = 0; i < that.data.adList.length;i++){
      wx.getImageInfo({ //将获取图片的信息
        src: that.data.uploadUrl + that.data.adList[i].imgPath,// 需要下载的图片
        success(res) {
          var filePath = res.path //得到本地的路径 
          wx.saveImageToPhotosAlbum({
            filePath: filePath,
            success(res) { 
              n++
              if (n == that.data.adList.length){
                wx.showToast({
                  title: '素材下载成功',
                  icon: 'success'
                })
              }
            }
          })
        }
      }) 

    } 
 
  },
  

 

  //获取短码encodeShort
  decodeShort() {
    this.setData({
      shareStart: !this.data.shareStart
    })
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/sys/comm/encodeShort',
      method: 'POST',
      data: {
        longCode: 'id=' + this.data.id + '&sharedCusId=' + wx.getStorageSync('userInfo').id
      }

    }, (res) => {
      this.getCode(res.shortCode)
    })
  }, 

  //获取二维吗
  getCode(scene) {
    var that = this
    _wxRequest.wxAjax({
      url: app.globalData.apiUrl + '/odr/mall/getWxaCodeUnlimit',
      contentType: "application/x-www-form-urlencoded",
      method: 'POST',
      data: {
        page: '/pages/good/detail/index',
        width: 750,
        scene
      }
    }, (res) => {
      console.log(res, 'getCode')
      that.setData({
        qrCode: res.url
      }, () => {
        that.toShare()
      })
    })
  },


  //分享
  toShare() {
    var qrCode = this.data.qrCode
    this.setData({
      shareImgTemplate: goodsShare.palette(qrCode, this.data.detail, 0)
    }); 
    wx.showLoading({
      title: "努力生成中..."
    });
  },

  //图片生成完成后呈现在页面上
  onShareImgOK(e) {
    this.setData({
      shareImgUrl: e.detail.path
    }); 
    wx.hideLoading();
    this.previewShareImg();
  },


  previewShareImg(e) {
    let url = this.data.shareImgUrl;
    wx.previewImage({
      current: url,
      urls: [url]
    });
  },





})